<!-- 登录页面组件 -->
<template>
  <div class="login-container">
    <!-- 登录/注册/修改密码卡片 -->
    <div class="login-card">
      <!-- 标题切换区域 -->
      <div class="title-switch">
        <span
            :class="['title-item', { active: currentMode === 'login' }]"
            @click="switchMode('login')"
        >登录</span>
        <span
            :class="['title-item', { active: currentMode === 'register' }]"
            @click="switchMode('register')"
        >注册</span>
        <span
            :class="['title-item', { active: currentMode === 'changePassword' }]"
            @click="switchMode('changePassword')"
        >修改密码</span>
      </div>

      <!-- 登录表单 -->
      <el-form
          v-if="currentMode === 'login'"
          :model="loginForm"
          :rules="loginRules"
          ref="loginFormRef"
          class="login-form"
      >
        <el-form-item prop="username">
          <el-input
              v-model="loginForm.username"
              placeholder="用户名"
              prefix-icon="el-icon-user"
          />
        </el-form-item>
        <el-form-item prop="password">
          <el-input
              v-model="loginForm.password"
              type="password"
              placeholder="密码"
              prefix-icon="el-icon-lock"
              show-password
          />
        </el-form-item>
        <el-button
            type="primary"
            class="submit-btn"
            @click="handleLogin"
            :loading="loading"
        >登录</el-button>
      </el-form>

      <!-- 注册表单 -->
      <el-form
          v-else-if="currentMode === 'register'"
          :model="registerForm"
          :rules="registerRules"
          ref="registerFormRef"
          class="register-form"
      >
        <el-form-item prop="username">
          <el-input
              v-model="registerForm.username"
              placeholder="用户名"
              prefix-icon="el-icon-user"
          />
        </el-form-item>
        <el-form-item prop="password">
          <el-input
              v-model="registerForm.password"
              type="password"
              placeholder="密码"
              prefix-icon="el-icon-lock"
              show-password
          />
        </el-form-item>
        <el-form-item prop="realName">
          <el-input
              v-model="registerForm.realName"
              placeholder="真实姓名"
              prefix-icon="el-icon-user"
          />
        </el-form-item>
        <el-form-item prop="email">
          <el-input
              v-model="registerForm.email"
              placeholder="邮箱"
              prefix-icon="el-icon-message"
          />
        </el-form-item>
        <el-button
            type="primary"
            class="submit-btn"
            @click="handleRegister"
            :loading="loading"
        >注册</el-button>
      </el-form>

      <!-- 修改密码表单 -->
      <el-form
          v-else
          :model="changePasswordForm"
          :rules="changePasswordRules"
          ref="changePasswordFormRef"
          class="change-password-form"
      >
        <el-form-item prop="username">
          <el-input
              v-model="changePasswordForm.username"
              placeholder="用户名"
              prefix-icon="el-icon-user"
          />
        </el-form-item>
        <el-form-item prop="oldPassword">
          <el-input
              v-model="changePasswordForm.oldPassword"
              type="password"
              placeholder="旧密码"
              prefix-icon="el-icon-lock"
              show-password
          />
        </el-form-item>
        <el-form-item prop="newPassword">
          <el-input
              v-model="changePasswordForm.newPassword"
              type="password"
              placeholder="新密码"
              prefix-icon="el-icon-lock"
              show-password
          />
        </el-form-item>
        <el-form-item prop="confirmPassword">
          <el-input
              v-model="changePasswordForm.confirmPassword"
              type="password"
              placeholder="确认新密码"
              prefix-icon="el-icon-lock"
              show-password
          />
        </el-form-item>
        <el-button
            type="primary"
            class="submit-btn"
            @click="handleChangePassword"
            :loading="loading"
        >修改密码</el-button>
      </el-form>
    </div>
  </div>
</template>

<script>
import { ref, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import request from '@/utils/request'  // 导入axios实例

export default {
  name: 'Login',
  setup() {
    const router = useRouter()
    // 控制当前显示的模式（登录/注册/修改密码）
    const currentMode = ref('login')
    const loading = ref(false) // 控制按钮加载状态
    const loginFormRef = ref(null)
    const registerFormRef = ref(null)
    const changePasswordFormRef = ref(null)

    // 登录表单数据
    const loginForm = reactive({
      username: '',
      password: ''
    })

    // 注册表单数据
    const registerForm = reactive({
      username: '',
      password: '',
      realName: '',
      email: ''
    })

    // 修改密码表单数据
    const changePasswordForm = reactive({
      username: '',
      oldPassword: '',
      newPassword: '',
      confirmPassword: ''
    })

    // 登录表单验证规则
    const loginRules = {
      username: [
        { required: true, message: '请输入用户名', trigger: 'blur' }
      ],
      password: [
        { required: true, message: '请输入密码', trigger: 'blur' }
      ]
    }

    // 注册表单验证规则
    const registerRules = {
      username: [
        { required: true, message: '请输入用户名', trigger: 'blur' }
      ],
      password: [
        { required: true, message: '请输入密码', trigger: 'blur' }
      ],
      realName: [
        { required: true, message: '请输入真实姓名', trigger: 'blur' }
      ],
      email: [
        { required: true, message: '请输入邮箱', trigger: 'blur' },
        { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
      ]
    }

    // 修改密码表单验证规则
    const changePasswordRules = {
      username: [
        { required: true, message: '请输入用户名', trigger: 'blur' }
      ],
      oldPassword: [
        { required: true, message: '请输入旧密码', trigger: 'blur' }
      ],
      newPassword: [
        { required: true, message: '请输入新密码', trigger: 'blur' },
        { min: 6, message: '密码长度不能小于6位', trigger: 'blur' }
      ],
      confirmPassword: [
        { required: true, message: '请确认新密码', trigger: 'blur' },
        {
          validator: (rule, value, callback) => {
            if (value !== changePasswordForm.newPassword) {
              callback(new Error('两次输入的密码不一致'))
            } else {
              callback()
            }
          },
          trigger: 'blur'
        }
      ]
    }

    // 切换登录/注册/修改密码模式
    const switchMode = (mode) => {
      currentMode.value = mode
      // 切换模式时重置表单
      if (mode === 'login') {
        loginForm.username = ''
        loginForm.password = ''
      } else if (mode === 'register') {
        registerForm.username = ''
        registerForm.password = '' 
        registerForm.realName = ''
        registerForm.email = ''
      } else {
        changePasswordForm.username = ''
        changePasswordForm.oldPassword = ''
        changePasswordForm.newPassword = ''
        changePasswordForm.confirmPassword = ''
      }
    }

    // 处理登录
    const handleLogin = async () => {
      if (!loginFormRef.value) return

      try {
        await loginFormRef.value.validate()
        loading.value = true

        // 调用登录接口
        const response = await request.post('/user/login', loginForm)
        if (response.code === 200) {
          localStorage.setItem('token', response.data.token)
          ElMessage.success('登录成功')
          router.push('/home')
        } else {
          ElMessage.error(response.message || '登录失败')
        }
      } catch (error) {
        ElMessage.error('登录失败，请检查网络连接')
      } finally {
        loading.value = false
      }
    }

    // 处理注册
    const handleRegister = async () => {
      if (!registerFormRef.value) return
      try {
        await registerFormRef.value.validate()
        loading.value = true

        // 调用注册接口
        const response = await request.post('/user/register', registerForm)
        if (response.code === 200) {
          ElMessage.success('注册成功')
          // 注册成功后切换到登录模式
          switchMode('login')
        } else {
          ElMessage.error(response.message || '注册失败')
        }
      } catch (error) {
        ElMessage.error('注册失败，请检查网络连接')
      } finally {
        loading.value = false
      }
    }

    // 处理修改密码
    const handleChangePassword = async () => {
      if (!changePasswordFormRef.value) return

      try {
        await changePasswordFormRef.value.validate()
        loading.value = true

        // 调用修改密码接口
        const response = await request.post('/user/changePassword', {
          username: changePasswordForm.username,
          password: changePasswordForm.oldPassword, // 旧密码
          newPassword: changePasswordForm.newPassword // 新密码
        })

        if (response.code === 200) {
          ElMessage.success('密码修改成功，请重新登录')
          // 修改成功后切换到登录模式
          switchMode('login')
        } else {
          ElMessage.error(response.message || '密码修改失败')
        }
      } catch (error) {
        ElMessage.error('密码修改失败，请检查网络连接')
      } finally {
        loading.value = false
      }
    }

    return {
      currentMode,
      loading,
      loginForm,
      registerForm,
      changePasswordForm,
      loginFormRef,
      registerFormRef,
      changePasswordFormRef,
      loginRules,
      registerRules,
      changePasswordRules,
      switchMode,
      handleLogin,
      handleRegister,
      handleChangePassword
    }
  }
}
</script>

<style scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  background-color: #f5f5f5;
}

.login-card {
  width: 400px;
  padding: 20px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.title-switch {
  display: flex;
  justify-content: center;
  margin-bottom: 30px;
}

.title-item {
  padding: 10px 20px;
  cursor: pointer;
  color: #606266;
  transition: all 0.3s;
}

.title-item.active {
  color: #409EFF;
  border-bottom: 2px solid #409EFF;
}

.login-form,
.register-form,
.change-password-form {
  margin-top: 20px;
}

.submit-btn {
  width: 100%;
  margin-top: 20px;
}
</style>
